package com.heima.search.service.Impl;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    public static final String APP_INFO_ARTICLE = "app_info_article";
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    EsService<SearchArticleVO> esService;
    @Autowired
    ApUserSearchService apUserSearchService;


    @Override
    public ResponseResult search(UserSearchDTO userSearchDto) {
        //1.参数检查(关键字)
        String searchWords = userSearchDto.getSearchWords();
        if (userSearchDto == null || StringUtils.isBlank(searchWords)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//===================  记录搜索历史记录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user !=null) userSearchDto.setEntryId(user.getId());
        // 异步调用保存用户输入关键词记录
        apUserSearchService.insert( userSearchDto);
        // ==========================
        //2 构建查询执行查询



        //2构建es搜索请求
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //2.1构建布尔请求条件

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //2.2根据关键词查询查询title字段
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", searchWords);
        boolQueryBuilder.must(queryBuilder);

        //2。3范围查询查询小于mindate的数据
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(userSearchDto.getMinBehotTime().getTime());
        //分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(userSearchDto.getPageSize());
        //按照发布时间倒序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //封装高亮条件
        //高亮三要素  字段 前置标签  后置标签
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        searchSourceBuilder.query(boolQueryBuilder);
        PageResponseResult searchResult = esService.search(searchSourceBuilder, SearchArticleVO.class, APP_INFO_ARTICLE);

        //4 返回结果 staticUrl 需要拼接 minIO文章服务器的前缀路径
        List<SearchArticleVO> list = (List<SearchArticleVO>) searchResult.getData();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SearchArticleVO searchArticleVO : list) {
                searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
            }
        }
        return searchResult;
    }

    @Override
    public void deleteArticle(String articleId) {

        esService.deleteById(APP_INFO_ARTICLE,articleId);
    }

    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,APP_INFO_ARTICLE);
    }
}
